import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))

import requests
import json
from reqapi.api import BaseApi

class PaymentStatusApi(BaseApi):
    def execute(self, order_no, pay_order_no, wait_payment_data_no, business_type=1, sub_bus_type=20000):
        """
        查询支付订单状态API
        
        Args:
            order_no: 订单号
            pay_order_no: 支付订单号
            wait_payment_data_no: 等待支付数据号
            business_type: 业务类型，默认1
            sub_bus_type: 子业务类型，默认20000
            
        Returns:
            dict: 包含以下字段的字典：
                - payStatus: 支付状态（1：待支付，2：支付成功，3：支付失败）
                - payStateMsg: 支付状态描述
                - paymentAmount: 支付金额（可能为空）
                - deductAmount: 抵扣金额（可能为空）
        """
        url = f"{self.BASE_URL}/api/youpin/bff/payment/v1/pay/order/status"
        data = {
            "businessType": business_type,
            "orderNo": order_no,
            "payOrderNo": pay_order_no,
            "subBusType": sub_bus_type,
            "waitPaymentDataNo": wait_payment_data_no,
            "Sessionid": self.device_id
        }
        headers = self.common_headers.copy()
        print("\n=== 请求信息 ===")
        print(f"请求URL: {url}")
        print(f"请求方法: POST")
        print(f"请求头: {json.dumps(headers, indent=2, ensure_ascii=False)}")
        print(f"请求数据: {json.dumps(data, indent=2, ensure_ascii=False)}")
        try:
            response = self.interceptor.send_request(url, json=data, headers=headers, need_encrypt=False)
            print("\n=== 响应信息 ===")
            if isinstance(response, dict):
                result = response
            elif hasattr(response, 'json'):
                result = response.json()
            else:
                result = response
            print(f"响应数据: {json.dumps(result, indent=2, ensure_ascii=False)}")
            if result.get('code') != 0:
                print(f"API返回错误: {result.get('msg', '未知错误')}")
                return None
            data = result.get('data', {})
            return {
                'payStatus': data.get('payStatus'),
                'payStateMsg': data.get('payStateMsg'),
                'paymentAmount': data.get('paymentAmount'),
                'deductAmount': data.get('deductAmount')
            }
        except Exception as e:
            print(f"请求发生错误: {str(e)}")
            return None

    def get_status_description(self, status):
        """
        获取支付状态的中文描述
        
        Args:
            status: 支付状态码
            
        Returns:
            str: 状态描述
        """
        status_map = {
            1: "待支付",
            2: "支付成功",
            3: "支付失败"
        }
        return status_map.get(status, "未知状态")


def main():
    """测试支付订单状态查询API"""
    try:
        # 使用实际的认证信息
        from com.db.order_account_manager import OrderAccountManager
        account_manager = OrderAccountManager()
        account = account_manager.get_account_by_id(1)
        
        if not account:
            print("无法获取ID为1的账号")
            return
        
        device_id = account.get('device_id', '')
        auth_token = account.get('uu_token', '')
        uk = account.get('uk', '')
        
        # 创建API实例
        api = PaymentStatusApi(
            device_token=device_id,  # 使用 device_id 作为 device_token
            device_id=device_id,
            auth_token=auth_token,
            uk=uk
        )
        
        # 调用API
        result = api.execute(
            order_no="2025020210964679356",
            pay_order_no="202502021866122896",
            wait_payment_data_no="202502021678799221"
        )
        
        # 打印结果
        print("\n=== 支付订单状态查询结果 ===")
        if result is None:
            print("支付订单状态查询失败，可能是登录信息失效或接口返回错误。")
        else:
            print(f"支付状态: {result['payStateMsg']} ({result['payStatus']})")
            if result.get('paymentAmount'):
                print(f"支付金额: {result['paymentAmount']}")
            if result.get('deductAmount'):
                print(f"抵扣金额: {result['deductAmount']}")
    except Exception as e:
        print(f"测试失败: {str(e)}")


if __name__ == "__main__":
    main()
